package cn.iocoder.yudao.module.system.controller.admin.mini.other.file;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.file.vo.MultipartFileToFile;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.file.vo.OssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Tag(name = "OSS文件上传")
@RestController
@RequestMapping("/pc/file")
public class FileUploadController {

    @Resource
    RedisTemplate<String, Object> redis;


    @Operation(summary = "文件上传")
    @PostMapping("/upload")
    @ResponseBody
    public CommonResult<String> upload(@RequestParam( value="multipartFile",required=false) MultipartFile multipartFile) throws Exception {
        if (multipartFile==null){
            throw new ServiceException(500,"multipartFile不能为空");
        }
        File file = MultipartFileToFile.multipartFileToFile(multipartFile);
        String result = OssUtil.uploadFileToOss(file);
        MultipartFileToFile.deleteTempFile(file);
        return CommonResult.success(result);
    }

    @Operation(summary = "文件上传返回固定url")
    @PostMapping("/uploadFixed")
    @ResponseBody
    public CommonResult<String> uploadFixed( @RequestParam( value="multipartFile",required=false) MultipartFile multipartFile) throws Exception {
        if (multipartFile==null){
            throw new ServiceException(500,"multipartFile不能为空");
        }
        File file = MultipartFileToFile.multipartFileToFile(multipartFile);
        String result = OssUtil.uploadFileToOss1(file);
        MultipartFileToFile.deleteTempFile(file);
        return CommonResult.success(result);
    }

    @PostMapping("setTemplate")
    @Operation(summary = "设置模版")
    public CommonResult<String> setTemplate(@RequestBody TemplateVo vo){
        String key="template";
        redis.opsForValue().set(key,vo.getList());
        return CommonResult.success("");
    }

    @PostMapping("getTemplate")
    @Operation(summary = "查看模版")
    public CommonResult<List<String>> getTemplate(){
        List<String> list=new ArrayList<>();
        Object o = redis.opsForValue().get("units");
        if(o!=null){
            list=(List<String>)o;
        }
        return CommonResult.success(list);
    }


}
@Data
class TemplateVo{
    List<String> list;
}
